import { Router } from 'express'
import { auth } from '../middlewares/auth'
import { validate } from '../middlewares/validate'
import { PaymentService } from '../services/payment/PaymentService'

const router = Router()
const paymentService = new PaymentService()

// 创建充值订单
router.post('/recharge', auth, validate('createOrder'), async (req, res, next) => {
  try {
    const { amount, payType } = req.body
    const order = await paymentService.createOrder(req.user._id, {
      amount,
      payType, // 'alipay' | 'wechat' | 'qq'
    })

    res.json({
      code: 200,
      message: '订单创建成功',
      data: order,
    })
  } catch (error) {
    next(error)
  }
})

// 支付回调
router.post('/notify/:platform', async (req, res, next) => {
  try {
    const { platform } = req.params
    await paymentService.handlePaymentNotify(platform, req.body)

    res.send('success') // 回调必须返回 success
  } catch (error) {
    next(error)
  }
})

// 查询订单状态
router.get('/order/:orderId', auth, async (req, res, next) => {
  try {
    const order = await paymentService.getOrderStatus(req.params.orderId)
    res.json({
      code: 200,
      message: '查询成功',
      data: order,
    })
  } catch (error) {
    next(error)
  }
})

export const paymentRoutes = router
